﻿using DeviceManagementLib;
using System;
using System.Management.Automation;

namespace DeviceManagementModule
{
    [Cmdlet(VerbsLifecycle.Uninstall, "Device", DefaultParameterSetName = "ByInstanceId", ConfirmImpact = ConfirmImpact.High, SupportsShouldProcess = true)]
    [OutputType(typeof(Device))]
    public class UninstallDeviceCmdlet : DeviceCmdletBase
    {
        [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByInstanceId")]
        public string InstanceId
        {
            get { return instanceId; }
            set { instanceId = value; }
        }

        [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByName")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        //-----------------------------------------------------------------------------------------

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
        }

        protected override void ProcessRecord()
        {
            try
            {
                devices = GetDevice();
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "ErrorGettingDevices", ErrorCategory.ReadError, null));
                return;
            }

            foreach (var device in devices)
            {
                try
                {
                    if (ShouldProcess(device.Name, "Uninstall Device"))
                    {
                        DeviceManagementLib.DeviceManagementLib.RemoveDevice(device.InstanceId);
                    }
                }
                catch(Exception ex)
                {
                    WriteError(new ErrorRecord(ex, "ErrorUninstallingDevices", ErrorCategory.WriteError, null));
                }
            }
        }

        protected override void EndProcessing()
        {
            base.EndProcessing();
        }
    }
}